<template> 
  <div>
    <el-upload
      action="https://cxq-edu.oss-cn-chengdu.aliyuncs.com"
      :data="dataObj"
      list-type="picture"
      :multiple="false" :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>
<script>
/**
 * TODO 该项目文件删除功能未做，后台接口为@DeleteMapping("/thirdparty/oss/deleteImg/{filename}")
 * {filename}为日期文件夹dir+filename
 **/
   import {policy} from './policy'
   import { getUUID } from '@/utils/myutils'

  export default {
    name: 'singleUpload',
    props: {
      value: String
    },
    computed: {
      imageUrl:{
        get(){return this.imgPreUrl + this.value;},
        set(v){}
      },
      imageName: {
        get(){
          if (this.value != null && this.value !== '') {
            return this.value.substr(this.value.lastIndexOf("/") + 1);
          } else {
            return null;
          }
        },
        set(v){}
        
      },
      fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function () {
          return this.value !== null && this.value !== ''&& this.value!==undefined;
          // return true;
        },
        set: function (newValue) {
          // console.log(newValue);
        }
      }
    },
    data() {
      return {
        imgPreUrl:'http://22478.xyz/',
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: '',
          newFileName:"",
          // callback:'',
        },
        dialogVisible: false,
      };
    },

    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        
        let fName = file.name;
        let newFileName = '';
        if(fName.split(".").length > 0 ){
            newFileName = getUUID()+"."+fName.split(".")[1];
        }
        let _self = this;
        return new Promise((resolve, reject) => {
          policy().then(response => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key = response.data.dir + newFileName;
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            _self.dataObj.newFileName = newFileName;
            resolve(true)
          }).catch(err => {
            reject(false)
          })
        })
      },
      handleUploadSuccess(res, file) {
        let myBackUrl = `${this.imgPreUrl}${this.dataObj.dir}/${this.dataObj.newFileName}`;
        console.log("上传成功...")
        this.showFileList = true;
        this.fileList.pop();
        this.imageName = this.dataObj.newFileName;
        this.imageUrl = myBackUrl;
        this.fileList.push({name: this.dataObj.newFileName, url: myBackUrl });
        this.emitInput(`${this.dataObj.dir}${this.dataObj.newFileName}`);
      }
    }
  }
</script>
<style>

</style>


